package com.newer.realm;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.newer.pojo.sys.User;
import com.newer.service.sys.iter.UserService;

/**
 * 自定义realm
 * 
 * 继承AuthorizingRealm
 * @author Administrator
 *
 */
public class LoginRealm extends AuthorizingRealm{
	/**
	 * 引入资源
	 */
	@Autowired
	private UserService userService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		/*SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		  //获得用户登陆名
		String username=principals.getPrimaryPrincipal().toString();
		//查询用户所拥有的角色
		Set<String> roles = userService.selectRoles(username);
		//设置角色
		authorizationInfo.setRoles(roles);
		//查询出用户所拥有的权限
		Set<String> permission = userService.selectPermission(username);
		//设置权限
		authorizationInfo.setStringPermissions(permission);
		return authorizationInfo;*/
		return null;
	}
	
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	       //获得用户登陆名
			String username= token.getPrincipal().toString();
			//通过用户名查询到该用户信息
			User user = userService.getByUserName(username);
			if(user!=null){
				Session session = SecurityUtils.getSubject().getSession();
				session.setAttribute("user", user);
				ByteSource credentialsSalt=ByteSource.Util.bytes(user.getUserName()); 
				//进行验证    
				//第三个参数是盐值 第四个参数可以随意写    
				return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), credentialsSalt, "LoginRealm");
			}
			throw new UnknownAccountException();
	}
}
